package cn.edu.klmy.controller;

import cn.edu.klmy.dao.*;
import cn.edu.klmy.models.param.SystemParam;
import cn.edu.klmy.models.schedule.RestrictionTime;
import cn.edu.klmy.models.student.Student;
import cn.edu.klmy.models.study.*;
import cn.edu.klmy.models.studylog.StudyLogSituation;
import cn.edu.klmy.models.teacher.Teacher;
import cn.edu.klmy.spring.security.core.userdetails.CourseSystemUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.datetime.DateFormatter;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;

/**
 * @author 顾伟
 *         创建日期：13-5-29
 */
@Controller
@RequestMapping("/study")
public class StudyController {
    @Autowired
    private IStudyDao studyDao;

    @Autowired
    private ITeacherDao teacherDao;

    @Autowired
    private IElectiveDao electiveDao;

    @Autowired
    private IBlackListDao blackListDao;

    @Autowired
    private IStudentDao studentDao;

    @Autowired
    private IScheduleDao scheduleDao;

    @RequestMapping("/list/no/election/{week}/{time}/students")
    @ResponseBody
    public List<Student> loadNoElectionStudents(HttpServletRequest request,@PathVariable int time,@PathVariable int week){
        HttpSession session = request.getSession();
        SystemParam systemParam = (SystemParam) session.getAttribute("param");
        int term = systemParam.getTerm();
        int section = systemParam.getSection();

        return studyDao.getNoElectionStudents(term, section, time, week);
    }

    @RequestMapping("/list/no/election/{week}/{time}/students/grade/")
    @ResponseBody
    public List<Student> loadNoElectionStudentsByConditions(HttpServletRequest request,@PathVariable int time,@PathVariable int week,@RequestParam String grade){
        HttpSession session = request.getSession();
        SystemParam systemParam = (SystemParam) session.getAttribute("param");
        int term = systemParam.getTerm();
        int section = systemParam.getSection();

        return studyDao.getNoElectionStudentsByConditions(term,section,time,week,grade);
    }

    @RequestMapping("/list/course/{scheduleId}/log/{week}/{time}/situation")
    @ResponseBody
    public List<StudyLogSituation> loadStudyLogSituation(HttpServletRequest request,@PathVariable int scheduleId,@PathVariable int time,@PathVariable int week){
        HttpSession session = request.getSession();
        SystemParam systemParam = (SystemParam) session.getAttribute("param");
        int term = systemParam.getTerm();
        int section = systemParam.getSection();

        return studyDao.getStudyLogSituation(scheduleId, term, section, time, week);
    }

    @RequestMapping("/list/course/{scheduleId}/{week}/{time}")
    @ResponseBody
    public List<Student> loadTeacherCourseStudentList(HttpServletRequest request,@PathVariable int scheduleId, @PathVariable int week, @PathVariable int time){
        HttpSession session = request.getSession();
        SystemParam systemParam = (SystemParam) session.getAttribute("param");
        int term = systemParam.getTerm();
        int section = systemParam.getSection();

        return studyDao.getTeacherCourseStudentList(scheduleId,term,section,time,week);
    }

    @RequestMapping("course/{scheduleId}/{week}/{time}/remove/student/{studentId}")
    @ResponseBody
    public boolean removeStudentFromCourseElective(HttpServletRequest request,@PathVariable int studentId,@PathVariable int scheduleId, @PathVariable int week, @PathVariable int time){
        HttpSession session = request.getSession();
        SystemParam systemParam = (SystemParam) session.getAttribute("param");
        int term = systemParam.getTerm();
        int section = systemParam.getSection();

        int count=electiveDao.deleteStudentElectiveCourse(studentId,scheduleId,term,section,week,time);
        if(count!=0){
            String teacherIDNo = ((CourseSystemUser) SecurityContextHolder.getContext()
                    .getAuthentication().getPrincipal()).getUser().getUserIdNo();
            Teacher teacher= teacherDao.getTeacher("TEACHER_ID_NO", "'"+teacherIDNo+"'");
            int teacherId=0;
            if(teacher!=null)
                teacherId=teacher.getId();
            int blackListId=blackListDao.addBlackList(teacherId);
            blackListDao.addStudentToBlackList(blackListId,studentId);
            return true;
        }
        return false;
    }

    @RequestMapping("/list/course/{scheduleId}/{week}/{time}/log/{logType}/date")
    @ResponseBody
    public List<String> loadCourseStudentLogsDate(HttpServletRequest request,@PathVariable int scheduleId, @PathVariable int week, @PathVariable int time, @PathVariable int logType){
        HttpSession session = request.getSession();
        SystemParam systemParam = (SystemParam) session.getAttribute("param");
        int term = systemParam.getTerm();
        int section = systemParam.getSection();

        return studyDao.getCourseLogsDate(scheduleId, term, section, time, week, logType);
    }

    @RequestMapping("/list/course/{scheduleId}/log/{week}/{time}/{logType}")
    @ResponseBody
    public List<CourseStudentLogs> loadCourseStudentLogs(HttpServletRequest request,@PathVariable int scheduleId, @PathVariable int week, @PathVariable int time, @PathVariable int logType){
        HttpSession session = request.getSession();
        SystemParam systemParam = (SystemParam) session.getAttribute("param");
        int term = systemParam.getTerm();
        int section = systemParam.getSection();

        String studentIDNo = ((CourseSystemUser) SecurityContextHolder.getContext()
                .getAuthentication().getPrincipal()).getUser().getUserIdNo();
        Student student = studentDao.getStudent("STUDENT_ID_NO", "'"+studentIDNo+"'");
        int studentId = 0;
        if (null != student)
            studentId = student.getId();

        return studyDao.getCourseStudentLogs(studentId,scheduleId,term,section,time,week,logType);

    }

    @RequestMapping("/list/course/{scheduleId}/{week}/{time}/student/log/{logType}/{logDate}")
    @ResponseBody
    public List<CourseStudentsLog> loadCourseStudentsLog(HttpServletRequest request,@PathVariable int scheduleId, @PathVariable int week, @PathVariable int time, @PathVariable int logType,@PathVariable String logDate) throws ParseException {
        HttpSession session = request.getSession();
        SystemParam systemParam = (SystemParam) session.getAttribute("param");
        int term = systemParam.getTerm();
        int section = systemParam.getSection();

        return studyDao.getCourseStudentsLog(scheduleId, term, section, time, week, logType, logDate);
    }

    @RequestMapping("/update/course/{scheduleId}/{week}/{time}/student/{studentId}/credits/{isObtainCredit}")
    @ResponseBody
    public boolean updateCourseStudentCredits(HttpServletRequest request,@PathVariable int studentId,
                                              @PathVariable int scheduleId,@PathVariable int time,@PathVariable int week,@PathVariable int isObtainCredit){
        HttpSession session = request.getSession();
        SystemParam systemParam = (SystemParam) session.getAttribute("param");
        int term = systemParam.getTerm();
        int section = systemParam.getSection();

        int count=studyDao.updateCourseStudentIsObtainCredit(studentId,scheduleId,term,section,time,week,isObtainCredit);
        if(count==0){
            return false;
        }
        return true;
    }

    @RequestMapping("/count/course/{scheduleId}/{week}/{time}/student/{studentId}/log")
    public String loadCourseStudentLogCountByType(Model model,HttpServletRequest request,@PathVariable int studentId,
                                                  @PathVariable int scheduleId,@PathVariable int time,@PathVariable int week){
        HttpSession session = request.getSession();
        SystemParam systemParam = (SystemParam) session.getAttribute("param");
        int term = systemParam.getTerm();
        int section = systemParam.getSection();

        int attendanceSumCount=studyDao.getCourseStudentLogCountByType(studentId,scheduleId,term,section,time,week,1,-1);
        model.addAttribute("attendanceSumCount",attendanceSumCount);
        int attendancePassCount=studyDao.getCourseStudentLogCountByType(studentId,scheduleId,term,section,time,week,1,1);
        model.addAttribute("attendancePassCount",attendancePassCount);

        int behaviorSumCount=studyDao.getCourseStudentLogCountByType(studentId,scheduleId,term,section,time,week,2,-1);
        model.addAttribute("behaviorSumCount",behaviorSumCount);
        int behaviorPassCount=studyDao.getCourseStudentLogCountByType(studentId,scheduleId,term,section,time,week,2,1);
        model.addAttribute("behaviorPassCount",behaviorPassCount);

        int homeworkSumCount=studyDao.getCourseStudentLogCountByType(studentId,scheduleId,term,section,time,week,3,-1);
        model.addAttribute("homeworkSumCount",homeworkSumCount);
        int homeworkPassCount=studyDao.getCourseStudentLogCountByType(studentId,scheduleId,term,section,time,week,3,1);
        model.addAttribute("homeworkPassCount",homeworkPassCount);

        int examSumCount=studyDao.getCourseStudentLogCountByType(studentId,scheduleId,term,section,time,week,4,-1);
        model.addAttribute("examSumCount",examSumCount);
        int examPassCount=studyDao.getCourseStudentLogCountByType(studentId,scheduleId,term,section,time,week,4,1);
        model.addAttribute("examPassCount",examPassCount);

        int isObtainCredits=studyDao.getCourseStudentIsObtainCredit(studentId,scheduleId,term,section,time,week);
        if(isObtainCredits==0)
            model.addAttribute("isObtainCredits","false");
        else
            model.addAttribute("isObtainCredits","true");

        model.addAttribute("studentId",studentId);

        return "studyLog";
    }

    @RequestMapping("/student/course/log/update")
    @ResponseBody
    public boolean updateCourseStudentLog(HttpServletRequest request)  {
        CourseStudentsLog courseStudentsLog=new CourseStudentsLog();
        courseStudentsLog.setLogId(Integer.parseInt(request.getParameter("logId")));
        courseStudentsLog.setLogContent(request.getParameter("logContent"));
        courseStudentsLog.setLogValue(Integer.parseInt(request.getParameter("logValue")));
        int count=studyDao.updateStudentCourseLogs(courseStudentsLog);

        if(count==0){
            return false;
        }
        return true;
    }

    @RequestMapping("/delete/course/{scheduleId}/{week}/{time}/log/{logType}/{logDate}")
    @ResponseBody
    public boolean deleteCourseStudentLogs(HttpServletRequest request,@PathVariable int scheduleId, @PathVariable int week, @PathVariable int time, @PathVariable int logType,@PathVariable String logDate) throws ParseException {
        HttpSession session = request.getSession();
        SystemParam systemParam = (SystemParam) session.getAttribute("param");
        int term = systemParam.getTerm();
        int section = systemParam.getSection();

        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");

        int insertCount=studyDao.deleteCourseLogs(scheduleId, term, section, time, week, logType, sdf.parse(logDate));
        if(insertCount==0){
            return false;
        }
        return true;
    }

    @RequestMapping("/add/course/{scheduleId}/{week}/{time}/log/{logType}/{logDate}")
    @ResponseBody
    public boolean addCourseStudentLogs(HttpServletRequest request,@PathVariable int scheduleId, @PathVariable int week, @PathVariable int time, @PathVariable int logType,@PathVariable String logDate) throws ParseException {
        HttpSession session = request.getSession();
        SystemParam systemParam = (SystemParam) session.getAttribute("param");
        int term = systemParam.getTerm();
        int section = systemParam.getSection();

        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");

        int insertCount=studyDao.addCourseLogs(scheduleId,term,section,time,week,logType,sdf.parse(logDate));
        if(insertCount==0){
            return false;
        }
        return true;
    }


    @RequestMapping("/list/attendance/course/table")
    @ResponseBody
    public List<AttendanceCourseOneWeek> loadAttendanceCourseTable(){
        List<AttendanceCourseOneWeek> attendanceCourseOneWeekList=new ArrayList<AttendanceCourseOneWeek>();
        AttendanceCourseOneWeek firstLessonOneWeek = new AttendanceCourseOneWeek("第一节课");
        AttendanceCourseOneWeek secondLessonOneWeek = new AttendanceCourseOneWeek("第二节课");
        AttendanceCourseOneWeek thirdLessonOneWeek = new AttendanceCourseOneWeek("第三节课");
        AttendanceCourseOneWeek forthLessonOneWeek = new AttendanceCourseOneWeek("第四节课");
        AttendanceCourseOneWeek fifthLessonOneWeek = new AttendanceCourseOneWeek("第五节课");
        AttendanceCourseOneWeek sixthLessonOneWeek = new AttendanceCourseOneWeek("第六节课");
        AttendanceCourseOneWeek seventhLessonOneWeek = new AttendanceCourseOneWeek("第七节课");
        AttendanceCourseOneWeek eighthLessonOneWeek = new AttendanceCourseOneWeek("第八节课");

        RestrictionTime restrictionTime = scheduleDao.getRestrictionTimeRule();
        if (restrictionTime.isHasFirstLesson()) {
            attendanceCourseOneWeekList.add(firstLessonOneWeek);
        }

        if (restrictionTime.isHasSecondLesson()) {
            attendanceCourseOneWeekList.add(secondLessonOneWeek);
        }

        if (restrictionTime.isHasThirdLesson()) {
            attendanceCourseOneWeekList.add(thirdLessonOneWeek);
        }

        if (restrictionTime.isHasForthLesson()) {
            attendanceCourseOneWeekList.add(forthLessonOneWeek);
        }

        if (restrictionTime.isHasFifthLesson()) {
            attendanceCourseOneWeekList.add(fifthLessonOneWeek);
        }

        if (restrictionTime.isHasSixthLesson()) {
            attendanceCourseOneWeekList.add(sixthLessonOneWeek);
        }

        if (restrictionTime.isHasSeventhLesson()) {
            attendanceCourseOneWeekList.add(seventhLessonOneWeek);
        }

        if (restrictionTime.isHasEighthLesson()) {
            attendanceCourseOneWeekList.add(eighthLessonOneWeek);
        }

        return attendanceCourseOneWeekList;

    }

    @RequestMapping("/list/table")
    @ResponseBody
    public List<TeacherCourseElectiveOneWeek> loadTeacherCourseTable(HttpServletRequest request){
        HttpSession session = request.getSession();
        SystemParam systemParam = (SystemParam) session.getAttribute("param");
        String teacherIDNo = ((CourseSystemUser) SecurityContextHolder.getContext()
                .getAuthentication().getPrincipal()).getUser().getUserIdNo();
        Teacher teacher= teacherDao.getTeacher("TEACHER_ID_NO", "'"+teacherIDNo+"'");
        int teacherId=0;
        if(teacher!=null)
            teacherId=teacher.getId();
        int term = systemParam.getTerm();
        int section = systemParam.getSection();

        List<TeacherCourseElective> teacherCourseElectiveList=studyDao.getTeacherCourseTable(teacherId,term,section);

        List<TeacherCourseElectiveOneWeek> teacherCourseElectiveOneWeekList = new ArrayList<TeacherCourseElectiveOneWeek>();


        TeacherCourseElectiveOneWeek firstLessonOneWeek = new TeacherCourseElectiveOneWeek("第一节课",1);
        TeacherCourseElectiveOneWeek secondLessonOneWeek = new TeacherCourseElectiveOneWeek("第二节课",2);
        TeacherCourseElectiveOneWeek thirdLessonOneWeek = new TeacherCourseElectiveOneWeek("第三节课",4);
        TeacherCourseElectiveOneWeek forthLessonOneWeek = new TeacherCourseElectiveOneWeek("第四节课",8);
        TeacherCourseElectiveOneWeek fifthLessonOneWeek = new TeacherCourseElectiveOneWeek("第五节课",16);
        TeacherCourseElectiveOneWeek sixthLessonOneWeek = new TeacherCourseElectiveOneWeek("第六节课",32);
        TeacherCourseElectiveOneWeek seventhLessonOneWeek = new TeacherCourseElectiveOneWeek("第七节课",64);
        TeacherCourseElectiveOneWeek eighthLessonOneWeek = new TeacherCourseElectiveOneWeek("第八节课",128);

        for (TeacherCourseElective teacherCourseElective : teacherCourseElectiveList) {
            int time = teacherCourseElective.getElectiveTime();
            switch (time) {
                case 1:
                    setWeekCourseTable(teacherCourseElective, firstLessonOneWeek);
                    break;
                case 2:
                    setWeekCourseTable(teacherCourseElective, secondLessonOneWeek);
                    break;
                case 4:
                    setWeekCourseTable(teacherCourseElective, thirdLessonOneWeek);
                    break;
                case 8:
                    setWeekCourseTable(teacherCourseElective, forthLessonOneWeek);
                    break;
                case 16:
                    setWeekCourseTable(teacherCourseElective, fifthLessonOneWeek);
                    break;
                case 32:
                    setWeekCourseTable(teacherCourseElective, sixthLessonOneWeek);
                    break;
                case 64:
                    setWeekCourseTable(teacherCourseElective, seventhLessonOneWeek);
                    break;
                case 128:
                    setWeekCourseTable(teacherCourseElective, eighthLessonOneWeek);
                    break;
            }
        }

        RestrictionTime restrictionTime = scheduleDao.getRestrictionTimeRule();
        if (restrictionTime.isHasFirstLesson()) {
            teacherCourseElectiveOneWeekList.add(firstLessonOneWeek);
        }

        if (restrictionTime.isHasSecondLesson()) {
            teacherCourseElectiveOneWeekList.add(secondLessonOneWeek);
        }

        if (restrictionTime.isHasThirdLesson()) {
            teacherCourseElectiveOneWeekList.add(thirdLessonOneWeek);
        }

        if (restrictionTime.isHasForthLesson()) {
            teacherCourseElectiveOneWeekList.add(forthLessonOneWeek);
        }

        if (restrictionTime.isHasFifthLesson()) {
            teacherCourseElectiveOneWeekList.add(fifthLessonOneWeek);
        }

        if (restrictionTime.isHasSixthLesson()) {
            teacherCourseElectiveOneWeekList.add(sixthLessonOneWeek);
        }

        if (restrictionTime.isHasSeventhLesson()) {
            teacherCourseElectiveOneWeekList.add(seventhLessonOneWeek);
        }

        if (restrictionTime.isHasEighthLesson()) {
            teacherCourseElectiveOneWeekList.add(eighthLessonOneWeek);
        }

        return teacherCourseElectiveOneWeekList;
    }

    private void setWeekCourseTable(TeacherCourseElective teacherCourseElective, TeacherCourseElectiveOneWeek teacherCourseElectiveOneWeek) {
        int week = teacherCourseElective.getElectiveWeek();
        switch (week) {
            case 1:
                teacherCourseElectiveOneWeek.setMondayCourse(teacherCourseElective);
                break;
            case 2:
                teacherCourseElectiveOneWeek.setTuesdayCourse(teacherCourseElective);
                break;
            case 4:
                teacherCourseElectiveOneWeek.setWednesdayCourse(teacherCourseElective);
                break;
            case 8:
                teacherCourseElectiveOneWeek.setThursdayCourse(teacherCourseElective);
                break;
            case 16:
                teacherCourseElectiveOneWeek.setFridayCourse(teacherCourseElective);
                break;
            case 32:
                teacherCourseElectiveOneWeek.setSaturdayCourse(teacherCourseElective);
                break;
            case 64:
                teacherCourseElectiveOneWeek.setSundayCourse(teacherCourseElective);
                break;
        }
    }
}
